from typing import List
from fastapi import APIRouter, File, UploadFile, Form, HTTPException
from datetime import datetime
import os
from fastapi.responses import JSONResponse
import json
import os
from pathlib import Path

from app.models.ifc_models import UploadResponse, AnalysisResult
from app.services.platform_service import platform_service
from app.services.ifc_service import IFCService

router = APIRouter(tags=["platform"])

@router.post("/upload", response_model=UploadResponse)
async def upload_ifc_file(
    file: UploadFile = File(...),
    building_type: str = Form("commercial", description="建筑类型: residential, commercial, industrial")
):
    """上传IFC文件并启动分析"""
    
    if not file.filename.endswith('.ifc'):
        raise HTTPException(status_code=400, detail="请上传IFC格式文件")
    
    if file.size > 300 * 1024 * 1024:  # 300MB限制
        raise HTTPException(status_code=400, detail="文件大小不能超过300MB")
    
    try:
        # 保存上传文件
        temp_dir = Path("temp")
        temp_dir.mkdir(exist_ok=True)
        temp_file = temp_dir / f"{file.filename}"
        
        with open(temp_file, "wb") as buffer:
            content = await file.read()
            buffer.write(content)
        
        # 转换为JSON
        ifc_service = IFCService()
        json_data = await ifc_service.convert_ifc_to_json(str(temp_file))
        
        # 保存JSON文件
        json_file = temp_dir / f"{file.filename.replace('.ifc', '.json')}"
        with open(json_file, "w", encoding="utf-8") as f:
            json.dump(json_data, f, ensure_ascii=False, indent=2)
        
        # 启动平台分析
        result = await platform_service.process_upload(
            str(json_file), 
            file.filename, 
            building_type
        )
        
        # 临时文件将在异步分析完成后由平台服务清理
        # 不要在这里删除，因为异步分析还需要这些文件
        
        return {
            "upload_id": result["upload_id"],
            "status": result["status"],
            "message": result["message"],
            "file_name": file.filename,
            "file_size": len(content),
            "upload_time": datetime.now(),
            "analysis_url": result["analysis_url"],
            "progress": 0
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"处理失败: {str(e)}")

@router.get("/analysis/{upload_id}")
async def get_analysis_result(upload_id: str):
    """获取分析结果"""
    try:
        result = await platform_service.get_analysis_result(upload_id)
        return result
    except ValueError as e:
        raise HTTPException(status_code=404, detail=str(e))

@router.get("/history", response_model=List[UploadResponse])
async def get_upload_history(limit: int = 10):
    """获取上传历史"""
    history = await platform_service.get_upload_history(limit)
    return [
        {
            "upload_id": item["upload_id"],
            "file_name": item["filename"],
            "file_size": 0,
            "status": item["status"],
            "message": "",
            "upload_time": item["upload_time"],
            "analysis_url": f"/api/analysis/{item['upload_id']}" if item["status"] == "completed" else None,
            "progress": 0
        }
        for item in history
    ]

@router.get("/health")
async def health_check():
    """健康检查"""
    return {"status": "healthy", "service": "bim-compliance-platform"}

@router.get("/demo")
async def get_demo_data():
    """获取演示数据"""
    return {
        "upload_id": "demo-001",
        "status": "completed",
        "overall_score": 82,
        "risk_level": "中等",
        "summary": "共发现3项合规问题，需要重点关注2项",
        "findings": [
            {
                "id": "F001",
                "category": "消防安全",
                "severity": "中等",
                "title": "消防通道宽度不足",
                "description": "主消防通道宽度仅为3.2米，低于规范要求的4米",
                "location": "主入口大厅",
                "cost_impact": 15000,
                "timeline_impact": 5,
                "suggested_fix": "扩大消防通道至4米以上"
            },
            {
                "id": "F002",
                "category": "无障碍设计",
                "severity": "轻微",
                "title": "坡道坡度超标",
                "description": "无障碍坡道坡度为8%，超过规范要求的6%",
                "location": "主入口",
                "cost_impact": 5000,
                "timeline_impact": 2,
                "suggested_fix": "调整坡道设计或增加扶手"
            },
            {
                "id": "F003",
                "category": "节能标准",
                "severity": "严重",
                "title": "外墙保温厚度不足",
                "description": "外墙保温层厚度仅为50mm，低于节能规范要求的80mm",
                "location": "北向外墙",
                "cost_impact": 25000,
                "timeline_impact": 8,
                "suggested_fix": "增加保温层厚度至80mm"
            }
        ],
        "recommendations": [
            "优先处理严重级别的问题",
            "建议聘请专业合规顾问进行详细审查",
            "制定分阶段整改计划"
        ],
        "cost_estimate": {
            "total": 45000,
            "urgent": 31500,
            "optional": 13500
        },
        "timeline_estimate": {
            "total_days": 8,
            "urgent_days": 5
        }
    }

@router.get("/demo/enhanced")
async def get_enhanced_demo_data():
    """获取增强分析演示数据"""
    return {
        "upload_id": "demo-enhanced-001",
        "status": "completed",
        "overall_score": 85,
        "risk_level": "低风险",
        "summary": "建筑结构分析完成，发现5项需要关注的问题",
        "project_info": {
            "name": "三层办公楼建筑",
            "building_type": "办公建筑",
            "total_elements": 358,
            "upload_time": "2024-12-19 10:30:00"
        },
        "analysis": {
            "fire_safety": {
                "fire_rated_elements": [
                    {"name": "防火墙_001", "fire_rating": "2小时", "type": "墙", "location": "1层A区"},
                    {"name": "防火门_M1027", "fire_rating": "1.5小时", "type": "门", "location": "主入口"},
                    {"name": "防火卷帘_R001", "fire_rating": "3小时", "type": "卷帘", "location": "地下车库"}
                ],
                "fire_doors_count": 8,
                "emergency_exits": [
                    {"name": "安全出口_01", "width": 1200, "location": "主入口"},
                    {"name": "安全出口_02", "width": 1000, "location": "侧门"},
                    {"name": "楼梯间出口", "width": 1100, "location": "楼梯间"}
                ],
                "fire_rating_distribution": {
                    "1小时": 12,
                    "1.5小时": 8,
                    "2小时": 15,
                    "3小时": 5
                }
            },
            "door_window_details": {
                "doors": {
                    "total_count": 19,
                    "fire_rated_count": 12,
                    "total_area": 45.6,
                    "detailed_listings": [
                        {"name": "主入口门", "width": 1200, "height": 2200, "area": 2.64, "type": "防火门"},
                        {"name": "办公室门_01", "width": 900, "height": 2100, "area": 1.89, "type": "普通门"},
                        {"name": "会议室门", "width": 1000, "height": 2100, "area": 2.1, "type": "防火门"}
                    ]
                },
                "windows": {
                    "total_count": 54,
                    "total_area": 186.5,
                    "detailed_listings": [
                        {"name": "办公室窗_01", "width": 1500, "height": 1200, "area": 1.8, "type": "铝合金窗"},
                        {"name": "会议室窗", "width": 2000, "height": 1500, "area": 3.0, "type": "断桥铝窗"}
                    ]
                }
            },
            "structural_analysis": {
                "load_bearing_elements": {
                    "walls": [
                        {"name": "承重墙_W1", "fire_rating": "2小时", "thickness": 240, "material": "钢筋混凝土"},
                        {"name": "承重墙_W2", "fire_rating": "2.5小时", "thickness": 300, "material": "钢筋混凝土"}
                    ],
                    "columns": [
                        {"name": "框架柱_C1", "fire_rating": "3小时", "size": "600x600", "material": "钢筋混凝土"},
                        {"name": "框架柱_C2", "fire_rating": "3小时", "size": "500x500", "material": "钢筋混凝土"}
                    ],
                    "beams": [
                        {"name": "框架梁_B1", "fire_rating": "2小时", "size": "300x600", "material": "钢筋混凝土"}
                    ],
                    "floors": [
                        {"name": "楼板_F1", "fire_rating": "1.5小时", "thickness": 150, "material": "钢筋混凝土"}
                    ]
                },
                "material_summary": {
                    "concrete": 245.8,
                    "steel": 45.2,
                    "masonry": 156.3
                },
                "fire_protection_summary": {
                    "fire_rated_elements": 89,
                    "total_fire_rating_hours": 156.5
                }
            }
        },
        "findings": [
            {
                "id": "F001",
                "category": "消防安全",
                "severity": "中等",
                "title": "部分防火门缺少自动关闭装置",
                "description": "发现3扇防火门未安装自动关闭装置，可能影响防火分区完整性",
                "location": "2层走廊",
                "cost_impact": 8000,
                "timeline_impact": 3,
                "suggested_fix": "为防火门安装经认证的自动关闭装置"
            },
            {
                "id": "F002",
                "category": "门窗设计",
                "severity": "轻微",
                "title": "部分窗户开启方式不符合规范",
                "description": "4扇高层窗户采用外开方式，存在安全隐患",
                "location": "3层办公室",
                "cost_impact": 3000,
                "timeline_impact": 1,
                "suggested_fix": "更换为内开或推拉式窗户"
            },
            {
                "id": "F003",
                "category": "结构安全",
                "severity": "轻微",
                "title": "部分梁柱节点设计需优化",
                "description": "3处梁柱节点钢筋锚固长度略显不足",
                "location": "1层框架节点",
                "cost_impact": 5000,
                "timeline_impact": 2,
                "suggested_fix": "增加节点区钢筋锚固长度"
            }
        ],
        "recommendations": [
            "优先处理消防安全相关问题",
            "建议对防火分区进行全面检查",
            "制定分阶段整改计划，优先处理高风险区域"
        ],
        "cost_estimate": {
            "total": 16000,
            "urgent": 8000,
            "optional": 8000
        },
        "timeline_estimate": {
            "total_days": 6,
            "urgent_days": 3
        }
    }